<script lang="ts" setup>
import { deleteRuleAPI,
getRuleListAPI } from '@/apis/car'
import type { Rule, RuleListParams } from '@/types/car'
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, reactive } from 'vue'
import { utils, writeFileXLSX } from 'xlsx'

const ruleList = ref<Rule[]>([])
const params = reactive<RuleListParams>({
  page: 1,
  pageSize: 5
})
const total = ref(0)
const dialogVisible = ref(false)

// 获取规则列表
const getRuleList = async () => {
  const res = await getRuleListAPI(params)
  ruleList.value = res.data.rows
  total.value = res.data.total
}
getRuleList()

// 计费规则 -- 第一个参数是键类型  ---  第二个参数是值类型
const chargeTypeMap = new Map<Rule['chargeType'], string>([
  // [key, value] 键值对
  ['duration', '时长收费'],
  ['turn', '按次收费'],
  ['partition', '分段消费']
])

// 导出Excel
const exportToExcel = ()=>{
  // 1. 创建一个新的工作簿
  const workbook = utils.book_new()
  // 2. 创建一个工作表 要求一个对象数组格式（可以根据需要创建多个）
  const worksheet = utils.json_to_sheet(ruleList.value.map((item, index) => ({
    ...item,
    id: index + 1,
    chargeType: chargeTypeMap.get(item.chargeType)
  })))
  // 3. 把工作表添加到工作簿  Data为工作表名称
  utils.book_append_sheet(workbook, worksheet, 'Data')
  // 改写表头
  utils.sheet_add_aoa(worksheet, [
    ['序号', '计费规则编号', '计费规则名称', '免费时长(分钟)', '收费上限(元)', '计费方式', '计费规则']
  ], { origin: 'A1' })
  // 4. 导出方法进行导出
  writeFileXLSX(workbook, '计费规则表.xlsx')
}

// 删除业务
const delRule = async (row: Rule) => {
  await ElMessageBox.confirm(
    "确定删除该计费规则吗？",
    "确定删除吗?",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
  await deleteRuleAPI(row.id!)
  getRuleList()
  ElMessage.success('删除成功')
}

// 弹窗实例
const addFormRef = ref()
// 开启弹窗
const onOpenDialog = () => {
  dialogVisible.value = true
}

// 关闭弹窗
const onCloseDialog = () => {
  dialogVisible.value = false
  addFormRef.value.resetFields()
}

// 添加规则 ---------------------------------
// 添加规则参数 
const addRulePropms = ref<Rule>({
  /**
   * 收费上限
   */
  chargeCeiling: undefined,
  /**
   * 收费类型，时长收费:duration,按次收费:turn,分段收费:partition
   */
  chargeType: 'duration',
  /**
   * 时长计费单位价格
   */
  durationPrice: undefined,
  /**
   * 时长计费单位时间
   */
  durationTime: undefined,
  /**
   * 时长收费类型 minute:分钟，hour:小时
   */
  durationType: 'minute',
  /**
   * 免费时长，单位:分钟
   */
  freeDuration: undefined,
  /**
   * 分段收费:段内费用
   */
  partitionFramePrice: undefined,
  /**
   * 分段收费:段内时间
   */
  partitionFrameTime: undefined,
  /**
   * 分段收费:超出范围收费价钱
   */
  partitionIncreasePrice: undefined,
  /**
   * 分段收费:超出时间
   */
  partitionIncreaseTime: undefined,
  /**
   * 计费规则名称
   */
  ruleName: '',
  /**
   * 计费规则编号
   */
  ruleNumber: '',
  /**
   * 按次收费：每次价格
   */
  turnPrice: undefined
})

</script>

<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="onOpenDialog">增加停车计费规则</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上限(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式">
          <template #default="{row}">
            {{ chargeTypeMap.get(row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column label="计费规则" prop="ruleNameView" />
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="{ row }">
            <el-button size="small" type="primary" link>编辑</el-button>
            <el-button size="small" type="danger" link @click="delRule(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page-container" style="margin-top: 20px;">
      <el-pagination 
        layout="total, prev, pager, next, sizes, jumper" 
        :page-sizes="[2, 5, 10, 20, 100]"
        :total="total"
        v-model:current-page="params.page" 
        v-model:page-size="params.pageSize"
        @change="getRuleList()"
      />
    </div>
    <!-- 弹框区域 -->
    <el-dialog :title="'添加计费规则'" @close="onCloseDialog" v-model="dialogVisible" width="600px">
      <!-- 表单模版 -->
      <div class="form-container">
        {{ addRulePropms }}
        <el-form ref="addFormRef" :model="addRulePropms" label-position="top">
          <el-form-item label="计费规则编号">
            <el-input v-model="addRulePropms.ruleNumber" placeholder="请输入计费规则编号"></el-input>
          </el-form-item>
          <el-form-item label="计费规则名称">
            <el-input v-model="addRulePropms.ruleName" placeholder="请输入计费规则名称"></el-input>
          </el-form-item>
          <el-form-item label="计费方式 （全天收费）">
            <div>
              <el-radio-group v-model="addRulePropms.chargeType">
                <el-radio value="duration" border>时长收费</el-radio>
                <el-radio value="turn" border>按次收费</el-radio>
                <el-radio value="partition" border>分段收费</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
          <div v-if="addRulePropms.chargeType === 'duration'">
            <div class="time">
              <el-form-item label="免费时长(分钟)">
                <div style="display: flex;">
                  <el-input v-model="addRulePropms.freeDuration" placeholder="请输入免费时长" /><div style="width: 36px">分钟</div>
                </div>
              </el-form-item>
              <el-form-item label="收费上限(元)">
                <div style="display: flex;">
                  <el-input v-model="addRulePropms.chargeCeiling" placeholder="请输入收费上限" />元
                </div>
              </el-form-item>
            </div >
            <el-form-item label="计费规则">
              <div class="time">
              <el-input placeholder="请输入"></el-input>
              <el-select></el-select>
              <el-input></el-input>
            </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
           <el-button @click="onCloseDialog">取 消</el-button>
           <el-button type="primary">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.time{
  display: flex;
}
.rule-container {
  padding: 20px;
  background-color: #fff;
}

.rules .el-form-item {
  padding: 0 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>